<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-16
 * Time: 21:57
 */

namespace plugin\csauto\app\service;

use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\model\TorrentListModel;
use support\Log;

/**
 * Class LoadMonitorService
 * 下载器负载监控服务
 * @package plugin\csauto\app\service
 */
class LoadMonitorService
{
    /**
     * 生成负载均衡报告
     * @return array
     */
    public static function generateLoadReport()
    {
        $downloaders = DownloaderModel::where('status', 1)->get();
        $report = [
            'timestamp' => date('Y-m-d H:i:s'),
            'total_downloaders' => $downloaders->count(),
            'downloaders' => []
        ];

        foreach ($downloaders as $downloader) {
            $downloaderData = [
                'id' => $downloader->id,
                'name' => $downloader->d_name,
                'status' => $downloader->status,
                'task_limit' => $downloader->getEffectiveTaskLimit(),
                'task_size' => $downloader->task_size,
                'current_load' => LoadBalancerService::calculateLoad($downloader),
                'active_tasks' => TorrentTaskModel::where('downloader_id', $downloader->id)->where('status', 1)->count(),
                'capacity_usage' => self::getCapacityUsage($downloader),
                'health_status' => self::getHealthStatus($downloader)
            ];

            $report['downloaders'][] = $downloaderData;
        }

        return $report;
    }

    /**
     * 获取下载器健康状态
     * @param DownloaderModel $downloader
     * @return string
     */
    private static function getHealthStatus(DownloaderModel $downloader)
    {
        $load = LoadBalancerService::calculateLoad($downloader);

        if ($load < 0.3) {
            return '健康';
        } elseif ($load < 0.7) {
            return '正常';
        } elseif ($load < 0.9) {
            return '繁忙';
        } else {
            return '过载';
        }
    }

    /**
     * 获取下载器容量使用情况
     * @param DownloaderModel $downloader
     * @return array
     */
    private static function getCapacityUsage(DownloaderModel $downloader)
    {
        $activeTasks = TorrentTaskModel::where('downloader_id', $downloader->id)
            ->where('status', '>=', 1)
            ->where('status', '<', 99)
            ->where('down_status', '>', 0)
            ->get();

        $currentSizeUsage = 0;
        $taskSizes = [];

        foreach ($activeTasks as $task) {
            $torrent = TorrentListModel::where('site_id', $task->site_id)
                ->where('torrent_id', $task->torrent_id)
                ->first();

            if ($torrent) {
                $sizeGB = HelperService::convertToGB($torrent->torrents_size);
                $currentSizeUsage += $sizeGB;
                $taskSizes[] = [
                    'torrent_id' => $task->torrent_id,
                    'size_gb' => $sizeGB
                ];
            }
        }

        return [
            'used' => $currentSizeUsage,
            'total' => $downloader->task_size,
            'percentage' => $downloader->task_size > 0 ? ($currentSizeUsage / $downloader->task_size) * 100 : 0,
            'tasks' => $taskSizes
        ];
    }

    /**
     * 记录负载报告到日志
     * @return void
     */
    public static function logLoadReport()
    {
        $report = self::generateLoadReport();

        addlog('负载监控报告', json_encode($report, JSON_UNESCAPED_UNICODE));

        // 记录每个下载器的详细状态
        foreach ($report['downloaders'] as $downloader) {
            addlog('下载器状态',
                "ID：{$downloader['id']}, 名称：{$downloader['name']}, 状态：{$downloader['health_status']}, " .
                "负载：{$downloader['current_load']}, 任务：{$downloader['active_tasks']}/{$downloader['task_limit']}, " .
                "容量：{$downloader['capacity_usage']['percentage']}%"
            );
        }
    }

    /**
     * 获取负载均衡建议
     * @return array
     */
    public static function getLoadBalancingRecommendations()
    {
        $report = self::generateLoadReport();
        $recommendations = [];

        foreach ($report['downloaders'] as $downloader) {
            if ($downloader['current_load'] > 0.9) {
                $recommendations[] = "下载器 {$downloader['name']} (ID: {$downloader['id']}) 负载过高，建议减少任务分配";
            } elseif ($downloader['current_load'] < 0.2) {
                $recommendations[] = "下载器 {$downloader['name']} (ID: {$downloader['id']}) 负载很低，可以承担更多任务";
            }

            if ($downloader['capacity_usage']['percentage'] > 90) {
                $recommendations[] = "下载器 {$downloader['name']} (ID: {$downloader['id']}) 容量使用率过高，建议清理或扩容";
            }
        }

        if (empty($recommendations)) {
            $recommendations[] = "所有下载器负载均衡状态良好";
        }

        return $recommendations;
    }
}
